package banners

import (
	. "awesomeProject/goods-web/api"
	"awesomeProject/goods-web/forms"
	"awesomeProject/goods-web/global"
	"awesomeProject/goods-web/proto"
	"context"
	"github.com/gin-gonic/gin"
	"github.com/golang/protobuf/ptypes/empty"
	"net/http"
	"strconv"
)

func List(ctx *gin.Context) {

	rsp, err := global.GoodsSrvClient.BannerList(context.Background(), &empty.Empty{})
	if err != nil {
		HandleGrpcErrorToHttp(err, ctx)
		return
	}

	rspMap := make([]interface{}, 0)

	for _, data := range rsp.Data {

		BannerInfo := make(map[string]interface{})
		BannerInfo["id"] = data.Id
		BannerInfo["index"] = data.Index
		BannerInfo["image"] = data.Image
		BannerInfo["url"] = data.Url

		rspMap = append(rspMap, BannerInfo)
	}

	ctx.JSON(http.StatusOK, rspMap)
}

func New(ctx *gin.Context) {

	bannerForm := forms.BannerForm{}
	if err := ctx.ShouldBind(&bannerForm); err != nil {
		HandleValidateError(err, ctx)
		return
	}

	rsp, err := global.GoodsSrvClient.CreateBanner(context.Background(), &proto.BannerRequest{
		Image: bannerForm.Image,
		Url:   bannerForm.Url,
		Index: int32(bannerForm.Index),
	})
	if err != nil {
		HandleGrpcErrorToHttp(err, ctx)
		return
	}

	rspMap := make(map[string]interface{})

	rspMap["id"] = rsp.Id
	rspMap["url"] = rsp.Url
	rspMap["image"] = rsp.Image
	rspMap["index"] = rsp.Index

	ctx.JSON(http.StatusOK, rspMap)
}

func Delete(ctx *gin.Context) {

	idStr := ctx.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 32)
	if err != nil {
		HandleGrpcErrorToHttp(err, ctx)
		return
	}

	_, err = global.GoodsSrvClient.DeleteBanner(context.Background(), &proto.BannerRequest{
		Id: int32(id),
	})
	if err != nil {
		HandleGrpcErrorToHttp(err, ctx)
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "删除成功",
	})
}

func Update(ctx *gin.Context) {
	bannerForm := forms.BannerForm{}
	if err := ctx.ShouldBind(&bannerForm); err != nil {
		HandleValidateError(err, ctx)
		return
	}
	idStr := ctx.Param("id")
	id, err := strconv.ParseInt(idStr, 10, 32)
	if err != nil {
		HandleGrpcErrorToHttp(err, ctx)
		return
	}

	_, err = global.GoodsSrvClient.UpdateBanner(context.Background(), &proto.BannerRequest{
		Id:    int32(id),
		Url:   bannerForm.Url,
		Image: bannerForm.Image,
		Index: int32(bannerForm.Index),
	})
	if err != nil {
		HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"msg": "更新成功",
	})
}
